package com.jeesite.modules.dataScreen.web.vo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.ClassUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import cn.hutool.core.util.ReflectUtil;

@AllArgsConstructor
public class IndustryIndexFun<T> {

    private static final Map<String, Field> fieldNameCache = new ConcurrentHashMap<>();
    @Getter
    private String name;

    private Func1<T, ?> func;

    public void apply(T result, Map<String, IndustryIndexVo> dataMap) {
        IndustryIndexVo indexVo = dataMap.get(name);
        if (Objects.nonNull(indexVo)) {
            ReflectUtil.setFieldValue(result, getField(result), indexVo);
        }
    }

    public static <T> IndustryIndexFun<T> fun(String name, Func1<T, ?> func) {
        return new IndustryIndexFun<>(name, func);
    }

    private Field getField(Object object) {
        String key = ClassUtil.getClassName(object,true) + name;
        Field field = fieldNameCache.get(key);
        if (field == null) {
            field = ReflectUtil.getField(object.getClass(), LambdaUtil.getFieldName(func));
            fieldNameCache.put(key, field);
        }
        return field;
    }
}
